<script src="<?php echo $socketNode?>socket.io/socket.io.js"></script>
<script>var socket = io.connect('<?php echo $socketNode?>');</script>
<script src="<?php echo $baseurl?>public/js/nhatnv.js"></script>
<?php if (isset($_GET['tvshow_id'])){
    $tvshow_id = intval($_GET['tvshow_id']);
?>
<?php foreach( $get_tvshow as $itemtv ){
?>
<script>

socket.emit('jointvshow', <?php echo $tvshow_id?>, 'sys-admin');
socket.emit('get-analytic', <?php echo $tvshow_id?>);
//initCharts('start');
<?php if(@$infoStart->starting == 0):?>
var start_tvshow = 0;
<?php else:?>
var start_tvshow = 1;
<?php endif;?>
function popups(id_log)
{
    if(start_tvshow == 1)
    {
        var url = '<?php echo $baseurl.'add-vote?id='.$tvshow_id;?>&id_log='+id_log;
        OpenPop(url, 600, 600);
        //alert('<?php echo $baseurl.'add-vote?id='.$tvshow_id;?>&id_log='+id_log);
    }else{
        jAlert('Vui lòng bấm nút bắt đầu chương trình để thêm câu hỏi mới', 'Thông báo');
    }
}
</script>
<div class="row">
                <div class="col-lg-12">
                    <h1 class="page-header">Điều kiển : <?=$itemtv->name?> </h1>
                </div>
                <!-- /.col-lg-12 -->
            </div>
            <!-- /.row -->
            <div class="row">
                <div class="col-lg-12">
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            Số người tham gia chương trình : <abbr id="join1">0</abbr> người
                            <?php if(@$infoStart->starting == 0):?>
                            <span class="control-tv-show btn-start-tv-show" data-id="<?php echo $infoStart->cid.'_'.$infoStart->tsid?>" data-value='<?php echo json_encode((object)array('bg' => $infoStart->background, 'name' => $infoStart->name, 'logo' => $infoStart->logo));?>'>Bắt đầu chương trình</span>
                            <?php else:?>
                            <span class="control-tv-show btn-stop-tv-show" data-id="<?php echo $infoStart->cid.'_'.$infoStart->tsid?>" data-value='<?php echo json_encode((object)array('bg' => $infoStart->background, 'name' => $infoStart->name, 'logo' => $infoStart->logo));?>'>Kết thúc chương trình</span>
                            <?php endif;?>
                        </div>
                        <div class="panel-body">
                            <div class="row">
                                <div class="top_addques">
                                    <div class="logo_addques">
                                        <p class="title_addques">Đang cập nhật</p>
                                        <img src="<?=$baseurl.$itemtv->program_logo?>" onerror="this.src='<?=$baseurl?>public/images/no-image.png';"/>
                                    </div>
                                    <div class="chart_addques" style="text-align: center;">
                                        <p class="title_chart">
                                            <span class="label-span-title-chart">Thống kê trả lời câu hỏi hiện tại</span>
                                            <i style="float: right;margin-top: 5px;"><abbr id="join2">0</abbr> trả lời</i>
                                        </p>
                                        <div class="chart_statistics" id="container-chart" style="height: 150px;margin-top: 30px"><p style="margin-top: 15%;font-size: 30px;color: #ccc;display: inline-block;"> Thống kê, đang chờ ... </p></div>
                                    </div>
                                </div>
                                <div class="list_addques">
                                    <div class="ques_now">
                                        <p class="">Danh sách câu hỏi hiện tại</p>
                                        <table class="list_ques">
                                        <tbody id="start_vote">
                                        <?php if(!in_array($data_vote_is_start, array(null, '', '0'))):?>
                                            <?php foreach($data_vote_is_start AS $el=>$le):?>
                                            <?php $json = json_decode($le->content);?>
                                                <tr>
                                                    <td style="width: 50% !important;" class=""><?php echo strip_slashes($json->question);?></td>
                                                    <td class="rs_rs" style="width: 30% !important;text-align: center">
                                                        <?php $arr = array();?>
                                                        <?php foreach($json->choice AS $eel=>$lle):?>
                                                        <span>
                                                            <?php $arr[] = $lle[0]?>
                                                            <?php echo $lle[0]?>
                                                        </span>
                                                         <?php endforeach?>
                                                    </td>
                                                    <td><span id="start_vote_qa" data-id="<?php echo $le->qid.'_'.$le->tvshow_id.'_'.$le->cid.'_'.$le->isshare?>" data-value='<?php echo $le->content; ?>' style="padding: 10px 20px;background: #E80606;display: inline-block">Kết thúc</span></td>
                                                </tr>
                                            <?php endforeach;?>
                                        <?php else:?>
                                            <tr id="no-question">
                                                <td class="no-noiseu" colspan="2">Hiện tại chưa có câu hỏi nào.</td>
                                            </tr>
                                        <?php endif;?>
                                        <tr id="no-msg" style="display: none;">
                                            <td class="no-noiseu-msg" colspan="2">Hiện tại chưa có câu hỏi nào.</td>
                                        </tr>
                                        </tbody>
                                        </table>
                                    </div>
                                    <div class="ques_next">
                                    <p class="">Danh sách câu hỏi tiếp theo</p>
                                    <div class="addnewques">
                                        <span class="" onclick="popups(sessionStorage.id_log)">Thêm câu hỏi tiếp theo +</span>
                                    </div>
                                    
                                    <table class="list_ques">
                                    <tbody id="list-vote">
                                        <?php if(!in_array($data_vote, array(null, '', '0'))):?>
                                        <?php foreach($data_vote AS $el=>$le):?>
                                        <?php $json = json_decode($le->content);?>
                                            <tr>
                                                <td class="qs" style="width: 50% !important;"><?php echo strip_slashes($json->question);?></td>
                                                <td class="rs_rs" style="width: 30% !important;text-align: center">
                                                    <?php $arr = array();?>
                                                    <?php foreach($json->choice AS $eel=>$lle):?>
                                                    <span>
                                                        <?php $arr[] = $lle[0]?>
                                                        <?php echo $lle[0]?>
                                                    </span>
                                                     <?php endforeach?>
                                                </td>
                                                <td class="tools">
                                                    <span id="start_vote_qa" data-other='<?php echo json_encode((object)array('data' => $arr))?>' data-id="<?php echo $le->qid.'_'.$le->tvshow_id.'_'.$le->cid.'_'.$le->isshare?>" data-value='<?php echo $le->content; ?>' style="padding: 10px 20px;margin-right: 5px;;display: inline-block;float: left;">Bắt đầu</span>
                                                    <span class="delete_vote" data-id="<?php echo $le->qid;?>" style="padding: 10px 20px;background: #B00101">Xóa</span>
                                                </td>
                                            </tr>
                                        <?php endforeach; endif;?>
                                    </tbody>
                                    </table>
                                    </div>
                                </div>                      
                                <!-- /.col-lg-6 (nested) -->
                            </div>
                            <!-- /.row (nested) -->
                        </div>
                        <!-- /.panel-body -->
                    </div>
                    <!-- /.panel -->
                </div>
                <!-- /.col-lg-12 -->
            </div>
<?php
}
}else{
?>
<div class="row">
                <div class="col-lg-12">
                    <h1 class="page-header">Điều kiển chương trình</h1>
                </div>
                <!-- /.col-lg-12 -->
            </div>
            <!-- /.row -->
            <div class="row">
                <div class="col-lg-12">
                    <div class="panel panel-default">
                        <div class="panel-heading time_heading">
                            Thời gian hiện tại
                        </div>
                        <div class="panel-body">
                            <div class="row">
                                <div class="col-lg-6">
                                    <form action="" method="GET">
                                        <div class="form-group">
                                            <label>Tìm kiếm chương trình</label>
                                            <input class="form-control search_tvshow" value="" placeholder="Nhập từ khóa..."/>
                                            <p class="help-block">Bạn vui lòng nhập từ khóa có dấu để lọc chương trình</p>
                                        </div>
                                    </form>
                                    <div class="form-group">
                                        <label>Danh sách chương trình</label>
                                        <div class="list_tvshow">
                                             <ul>
                                            <?php foreach($list_tvshow as $item){?>
                                                <li data-id="<?=$item['id']?>" class="tvshow_click">
                                                    <span>
														 <span class="name"><?php echo $fview->cutString($item['name'],8); ?></span>
														<span class="starting">
														<?php if( $item['starting'] == 1 ){ echo "<span class='true'>Đang phát sóng</span>"; }?>
													</span>
													</span>
													
                                                </li>
                                            <?php } ?>
                                        </ul>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-lg-6">
                                    <h1 class="title_tvshow">Thông tin chương trình</h1>
                                    <div class="form-group">
                                        <label>Tên chương trình</label>
                                        <p class="form-control-static tvshow_name">Đang cập nhật</p>
                                    </div>
                                    <div class="form-group">
                                        <label>Thời gian lên sóng</label>
                                        <p class="form-control-static tvshow_schedule"></p>
                                    </div>
                                    <label>Hình ảnh đại diện</label>
                                        <div class="form-group tvshow_bg">
                                            <img src="" onerror="this.src='<?=$baseurl?>public/images/no-image.png';"/>
                                        </div>
                                    
                                    <button data-id="" type="submit" class="btn btn-success choice_tvshow">Chọn chương trình này</button>
                                    <button data-id="" type="reset" class="btn btn-success edit_tvshow">Chỉnh sửa</button>
                                    
                                </div>                                
                                <!-- /.col-lg-6 (nested) -->
                            </div>
                            <!-- /.row (nested) -->
                        </div>
                        <!-- /.panel-body -->
                    </div>
                    <!-- /.panel -->
                </div>
                <!-- /.col-lg-12 -->
            </div>
<?php } ?>

<script>


function disableF5(e) { if ((e.which || e.keyCode) == 116) e.preventDefault(); };
$(document).on("keydown", disableF5);

$(document).keyup(function(e) 
{
  if (e.keyCode == 27) { closeIframe(); }
});

<?php if(!in_array($data_vote_is_start, array(null, '', '0'))):?>
var next_step = 0;
<?php else:?>
var next_step = 1;
<?php endif;?>


socket.on('sendaddvotesuccess', function(data_)
{
    
    var id_show = '<?php echo @$tvshow_id; ?>';
    var id_show = id_show ? id_show : 0;
    $.ajax({
        type: 'GET',
        url: '<?php echo $baseurl?>get-vote-list',
        data: ({id: data_, tvshow_id: id_show}),
        success: function(data)
        {
            var html = data;
            $("#list-vote").append(html);
            setTimeout(function()
            {
                closeIframe();
            },1000);
        }
       });
});
        
socket.on('receiveAnalytic', function(analyticsRoom, id_tvshow, tanalyticsRoom, troom)
{
    var ids_show = '<?php echo @$tvshow_id?>';
    var ids_show = ids_show ? ids_show : 0;
   if(id_tvshow == ids_show)
    {
        $("#join1").text(troom);
        $("#join2").text(tanalyticsRoom);
        numAnalytics = 0;
        
        var data = analyticsRoom;
        var length_ = data.length;
        var _data = [];
        var count_rs = 0;
        for(iz = 1; iz < length_; iz++)
        {
            var npt = (data[iz] * 100) / tanalyticsRoom;
            var n = parseFloat(npt); 
            var pt = format_number(n,1);
            _data.push(pt);
        }
        updateChart(_data);
    }
   
});


socket.on('response-get-analytic', function(data_)
{
    
    if(localStorage.arr_cs != undefined)
    {
        var localArr = localStorage.arr_cs;
        var _arr_cs = JSON.parse(localArr).cs;
        var _length_arr_cs = Object.keys(_arr_cs).length;
        initCharts(_arr_cs, _length_arr_cs);
                                    
        var ids_show = '<?php echo @$tvshow_id?>';
        var ids_show = ids_show ? ids_show : 0;
        var id_tvshow_ = data_.id_tvshow;
       if(id_tvshow_ == ids_show)
        {
            $("#join1").text(data_.data1);
            $("#join2").text(data_.data2);
            numAnalytics = 0;
            
            var data = data_.analytics;
            
            var length_ = data.length;
            var _data = [];
            var count_rs = 0;
            for(iz = 1; iz < length_; iz++)
            {
                var npt = (data[iz] * 100) / data_.data2;
                var n = parseFloat(npt); 
                var pt = format_number(n,1);
                _data.push(pt);
            }
            updateChart(_data);
        }
    }
});


$(".tvshow_schedule").text(timeConverter(1414146535));

$('.search_tvshow').keyup(function(){
    var valThis = $(this).val().toLowerCase();
    $('.list_tvshow ul li').each(function(){
        var text = $(this).text().toLowerCase();
        (text.indexOf(valThis) >= 0) ? $(this).show() : $(this).hide();            
    });
}); 

$(document).on('click', '#start_vote #start_vote_qa', function()
{
  
    var _this = $(this);
    var ids = _this.data('id');
    var exp = ids.split('_');
    var id_question = exp[0];
    _this.html('Xin chờ').css('background', '#949494');

   $.ajax({
        type: "GET",
        url: '<?php echo $baseurl.'update-stop-question'?>',
        data:({id_question: id_question}),
        success: function(data){
            socket.emit('stop_vote', exp[1], id_question);
            var html = _this.data('id');
            next_step = 1;
            _this.parents('tr').remove();
            delete localStorage.arr_cs;
            socket.emit('clearAnalytic', exp[1]);
            $("#no-msg").show().find('td.no-noiseu-msg').html('Kết thúc thành công. Bạn có thể tiếp tục thêm câu hỏi khác');
        }
    });
});

$(document).on('click', '#list-vote #start_vote_qa', function()
{
        if(next_step == 1)
        {
            var _this = $(this);
            var ids = _this.data('id');
            var exp = ids.split('_');
            var id_question = exp[0];
            var data_ = _this.data('value');
            _this.html('Xin chờ').css('background', '#949494');
            $.ajax({
            type: "GET",
            url: '<?php echo $baseurl.'update-start-question'?>',
            data:({id_question: id_question}),
            success: function(data){
                
                var cc = JSON.parse(JSON.stringify(_this.data('other')));
                console.log('cc', cc);
                var arr_cs = cc.data;
                var arr_object = {};
                arr_object.cs = arr_cs;
                localStorage.arr_cs = JSON.stringify(arr_object);
                initCharts(arr_cs,arr_cs.length);
                
                socket.emit('sendOneVote', data_, exp[1], exp[2], id_question, exp[3]);
                socket.emit('clearAnalytic', exp[1]);
                $("#no-question").hide();$("#no-msg").hide();
                _this.parents('tr').find('#start_vote_qa').html('Kết thúc').css('background', '#E80606');
                _this.parents('tr').find('.delete_vote').remove();
                _this.parents('tr').find('#start_vote_qa').css('float', 'center');
                var html_ = _this.parents('tr');
                $("#start_vote").append(html_);
                next_step = 0;
            }
        }); // end ajax
        }else{
            jAlert('Vui lòng chọn dừng câu hỏi hiện tại để có thể bắt đầu 1 câu mới', 'Thông báo');
        }
        
});

$( document ).ready(function() {
    $(".control-tv-show").click(function()
    {
        var id_show = '<?php echo @$tvshow_id; ?>';
        var id_show = id_show ? id_show : 0;
        var name_show = '<?php echo @$itemtv->name?>';
        var ids = $(this).data('id');
        var exp = ids.split('_');
        var id_channel = exp[0];
        var id_show = exp[1];
        var dataTemplate = $(this).data('value');
        $.ajax({
            type: "GET",
            url: '<?php echo $baseurl.'update-tv-show'?>',
            data:({tvshow_id: id_show, tvshow_name: name_show, channel_id: id_channel}),
            success: function(data)
            {	
                var parse = JSON.parse(data);
                //console.log(parse);
                if(parse.set != 0 || parse.set == undefined || parse.set == "")
                {
                    start_tvshow = 1;
                    $('.control-tv-show').html('Kết thúc chương trình').removeClass('btn-start-tv-show').addClass('btn-stop-tv-show');
                    socket.emit('creattemplate', id_show, id_channel, dataTemplate, 'start');
                    sessionStorage.id_log = parse.id_log;
                }else if(parse.set == 0){
					alert("Kết thúc chương trình");
                    start_tvshow = 0;
                    $('.control-tv-show').html('Bắt đầu chương trình').removeClass('btn-stop-tv-show').addClass('btn-start-tv-show');
                    socket.emit('creattemplate', id_show, id_channel, dataTemplate, 'stop');
                    $.ajax({
                        type: "GET",
                        url: '<?php echo $baseurl.'stop-tv-show'?>',
                        data:({id_log: sessionStorage.id_log}),
                        success: function(data)
                        {
                            console.log('Stop TVShow!');
                            sessionStorage.id_log = 0;
                        }
                    });
                }
            }
        }); // end ajax
    })
    
    $(".list_tvshow li").click(function(){
        $( ".list_tvshow li" ).each(function( index, el ) {;
            $(this).removeClass('li_selected');
        });
        $(this).addClass("li_selected");
        var tvshow_id = $(this).data("id");
        $.ajax({
            type: "GET",
            url: '<?php echo $baseurl.'manage/control/ajaxGetTvshow'?>',
            data:{ 
                tvshow_id :tvshow_id
            },
            success: function(data)
            {
                var data_ = JSON.parse(data);
                $(".tvshow_name").html(data_[0].name);
                $(".tvshow_bg img").attr("src","<?=$baseurl?>"+data_[0].program_logo);
                $(".tvshow_schedule").html(timeConverter(data_[0].schedule));
                $(".choice_tvshow").attr("data-id",tvshow_id);
                $(".edit_tvshow").attr("data-id",tvshow_id);
            }
        }); // end ajax
		// click chọn chương trình
		$(".choice_tvshow").click(function(){      
			if( $(this).data("id") == "" ){
			}else{
				window.location.assign("<?=$baseurl?>manage/control/add-question?tvshow_id="+$(this).data("id"));
			}
			return false;
		});
		// click sửa chương trình
		$(".edit_tvshow").click(function(){
			if( $(this).data("id") == "" ){
			}else{
				window.location.assign("<?=$baseurl?>manage/content/edit-tvshow/"+$(this).data("id"));
			}
			return false;
		});
    });
	
	


	
 });
 
$(document).on('mouseover', '.hoverMouse', function()
{
    var id = $(this).data('id');
    $('#rs-'+id).css('display', 'block');
});

$(document).on('mouseout', '.hoverMouse', function()
{
    var id = $(this).data('id');
    $('#rs-'+id).css('display', 'none');
});


$(document).on('click', '.delete_vote', function()
{
    var _this = $(this);
    var id = _this.data('id');
    jConfirm('<center>Bạn có chắc chắn muốn xóa?</center>', 'Thông báo', function(r) {
	if(r == true)
    {
        $.ajax({
            type: 'GET',
            url: '<?=$baseurl.'delete-vote'?>',
            data: ({id: id}),
            success: function(data)
            {
                _this.parents('tr').remove();
            }
        });
    }
        
	});
    return false;
})

//disable F5
function disableF5(e) { if ((e.which || e.keyCode) == 116) e.preventDefault(); };
$(document).on("keydown", disableF5);
</script>